﻿///***************************************************************
/// 시  스  템 : Updms.Mny
/// 단위시스템 : MNY
/// 계      층 : Presentation Layer
/// 프로그램명 : Mny2011r
/// 파  일  명 : Mny2011r.aspx.cs
/// 설      명 : 연간출납분석표
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-08-05 송시명   최초 작성
///***************************************************************
using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Adapter;
using SMFramework.Data;
using SMFramework.Security;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Common.BaseClass;
using Updms.Mny.Exe;


namespace Updms.Mny
{
	public partial class Mny2011r : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Mny2011r";
		public static readonly string gs_path_info = "/updms/Mny/" + PID + ".aspx";

		Global global = new Global();
		Crypto crypto = new Crypto();

		//검색
		protected string kw1 = "";	// 기준년도

		//메뉴 선택값
		protected string gs_sm = "";

		// 페이지모드

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetBaseYear();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion	

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			
			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_base_year.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_base_year.SelectedValue = kw1;
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_base_year.SelectedValue;
					break;
			}
		}

		#endregion

		#region 마스터 Method (SetBaseYear, 전년, 당년, 차년)

		// 기준년도 설정
		private void SetBaseYear()
		{
			ddl_search_base_year.Items.Clear();

			int li_f_year = Convert.ToInt32(SEARCH_Y_MIN);
			int li_t_year = Convert.ToInt32(DateUtil.GetYearEx(1, "yyyy"));
			int li_c_year = Convert.ToInt32(DateUtil.GetYearEx(0, "yyyy"));
			for (int i = li_f_year; i <= li_t_year; i++)
			{
				string ls_year = i.ToString();
				ddl_search_base_year.Items.Add(new ListItem(ls_year, ls_year));
			}

			ddl_search_base_year.SelectedValue = li_c_year.ToString(); // 기본값은 현재년도
		}

		//전년, 차년버튼 누르면
		private void SetPrevNextYear(int pi_year_cnt)
		{
			string ls_year = ddl_search_base_year.SelectedValue;
			string ls_calc_year = Convert.ToString(Convert.ToInt32(ls_year) + pi_year_cnt);

			if (WebControlUtil.CheckDdlValue(ddl_search_base_year, ls_calc_year))
			{
				ddl_search_base_year.SelectedValue = ls_calc_year;
			}

			//버튼처리
			SetEnabledYearBtn();
		}

		//당년설정
		private void SetThisYear()
		{
			string ls_this_year = DateUtil.GetNow("yyyy");
			ddl_search_base_year.SelectedValue = ls_this_year;
			SetEnabledYearBtn();
		}

		//전년, 차년버튼 처리
		private void SetEnabledYearBtn()
		{
			ibtn_prev_year.Enabled = (ddl_search_base_year.SelectedIndex == 0) ? false : true;
			ibtn_next_year.Enabled = (ddl_search_base_year.SelectedIndex == ddl_search_base_year.Items.Count - 1) ? false : true;
		}

		#endregion

		#region 디테일 Method (SetChartByAccount, CreateFileReal)

		//계정별 라인챠트
		private void SetChartByAccount(int row_idx)
		{
			//시리즈
			chart_line.Data.Series = 1;
			string series = GridView1.Rows[row_idx].Cells[4].Text;
			series = ConversionUtil.ExtractStrBtwnChar(series, ";\">", "</a>");
			
			chart_line.Series[0].Text = series;

			//초기화
			chart_line.Data.Clear();

			double ld_avg = 0.0; //평균
			int li_sum = 0; //합계
			int li_cnt = 0; //금액이 0이상인 월의 수

			for (int i = 0; i < 12; i++)
			{
				int value = Convert.ToInt32(ConversionUtil.RemoveComma(ConversionUtil.ExtractStrBtwnChar(GridView1.Rows[row_idx].Cells[i + 5].Text, ");\">", "</span>")));
				
				//수동으로 데이터 바인딩
				chart_line.Data[0, i] = value;
				li_sum = li_sum + value;

				//X축 라벨링
				string ls_base_dt = "'" + ddl_search_base_year.SelectedValue.Substring(2, 2) + "." + DateUtil.ConvertMonthFormat((i + 1).ToString());
				chart_line.AxisX.Labels[i] = ls_base_dt;

				//0이상일때만 보여준다.
				if (chart_line.Data[0, i] > 0)
				{
					chart_line.Points[0, i].PointLabels.Visible = true;
					li_cnt++;
				}
				else
				{
					chart_line.Points[0, i].PointLabels.Visible = false;
				}
			}

			if (li_cnt > 0)
			{
				ld_avg = li_sum / li_cnt;
			}

			//CustomGridLine 초기화
			chart_line.AxisY.CustomGridLines.Clear();

			//CustomGridLine
			ChartFX.WebForms.CustomGridLine cgl1 = new ChartFX.WebForms.CustomGridLine();
			cgl1.Value = ld_avg;
			cgl1.Color = System.Drawing.Color.Red;
			cgl1.Width = 2;
			cgl1.Text = "Avg. : " + ld_avg.ToString("#,###.##");
			cgl1.Alignment = StringAlignment.Far;
			cgl1.LineAlignment = StringAlignment.Near;
			cgl1.TextColor = Color.Black;

			chart_line.AxisY.CustomGridLines.Add(cgl1);
			
			mpe_chart_line.Show();
		}

		//실제파일생성
		private void CreateFileReal(string ls_file_nm, DataSet ds)
		{
			try
			{
				string tableName = "UPDMS_MNY_REPORT";
				string ls_stream = FILE_PATH_FTP_UPLOAD + "\\" + ls_file_nm;
				FileInfo file = new FileInfo(ls_stream);

				StreamWriter sw = file.CreateText();

				sw.WriteLine(CommUtil.GetDefaultHtmlTag(PID, global.GetMenuTitle(PID, LANG_SET) + "(" + ddl_search_base_year.SelectedValue + ")"));
				sw.WriteLine("<table class=\"report\">");
				sw.WriteLine("<tr>");
				sw.WriteLine("<th>계정</th>");
				sw.WriteLine("<th>1월</th>");
				sw.WriteLine("<th>2월</th>");
				sw.WriteLine("<th>3월</th>");
				sw.WriteLine("<th>4월</th>");
				sw.WriteLine("<th>5월</th>");
				sw.WriteLine("<th>6월</th>");
				sw.WriteLine("<th>7월</th>");
				sw.WriteLine("<th>8월</th>");
				sw.WriteLine("<th>9월</th>");
				sw.WriteLine("<th>10월</th>");
				sw.WriteLine("<th>11월</th>");
				sw.WriteLine("<th>12월</th>");
				sw.WriteLine("<th>총액</th>");
				sw.WriteLine("</tr>");
				for (int i = 0; i < DataSetUtil.GetRowCount(ds, tableName); i++)
				{
					string viewOrder = DataSetUtil.GetFldStr(ds, tableName, i, "view_Order");
					string accountNm = DataSetUtil.GetFldStr(ds, tableName, i, "Account_Nm");
					double m01 = DataSetUtil.GetFldDbl(ds, tableName, i, "M01");
					double m02 = DataSetUtil.GetFldDbl(ds, tableName, i, "M02");
					double m03 = DataSetUtil.GetFldDbl(ds, tableName, i, "M03");
					double m04 = DataSetUtil.GetFldDbl(ds, tableName, i, "M04");
					double m05 = DataSetUtil.GetFldDbl(ds, tableName, i, "M05");
					double m06 = DataSetUtil.GetFldDbl(ds, tableName, i, "M06");
					double m07 = DataSetUtil.GetFldDbl(ds, tableName, i, "M07");
					double m08 = DataSetUtil.GetFldDbl(ds, tableName, i, "M08");
					double m09 = DataSetUtil.GetFldDbl(ds, tableName, i, "M09");
					double m10 = DataSetUtil.GetFldDbl(ds, tableName, i, "M10");
					double m11 = DataSetUtil.GetFldDbl(ds, tableName, i, "M11");
					double m12 = DataSetUtil.GetFldDbl(ds, tableName, i, "M12");
					double totalAmt = DataSetUtil.GetFldDbl(ds, tableName, i, "Total_Amt");

					//소계, 총계
					if (viewOrder == "AA001T" || viewOrder == "AA002T" || viewOrder == "AA003T")
					{
						sw.WriteLine("<tr class=\"sub_total\">");
					}
					else if (viewOrder == "AA004T")
					{
						sw.WriteLine("<tr class=\"total\">");
					}
					else
					{
						sw.WriteLine("<tr>");
					}

					sw.WriteLine("<td class=\"lbl\">" + accountNm + "</td>");
					sw.WriteLine("<td class=\"data\">" + m01.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m02.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m03.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m04.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m05.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m06.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m07.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m08.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m09.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m10.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m11.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + m12.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"total_amt\">" + totalAmt.ToString("#,###,##0") + "</td>");
					sw.WriteLine("</tr>");
				}
				sw.WriteLine("</table>");
				sw.WriteLine("</body>");
				sw.WriteLine("</html>");

				sw.Close();
			}
			catch (Exception e)
			{
				Base.AppFramework.SMEventLog.WriteExceptionLog(e);
				CallMsgBoxInAjax("MSG_ERR_122");	//파일을 생성하지 못했습니다
			}
		}

		#endregion

		#region CRUD (SelectProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_base_year", typeof(string), kw1);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			//검색
			using (Mny2011r_NT _Mny2011r_NT = new Mny2011r_NT())
			{
				lo_ds.Merge(_Mny2011r_NT.GetYearlyInOutAnalysisList(lo_dp));

				if (!DataSetUtil.CheckRowCount(lo_ds, "UPDMS_MNY_REPORT"))
				{
					CallMsgBoxInAjax("MSG_ERR_111");	// 등록된 내용이 없습니다
				}

				GridView1.DataSource = lo_ds;
				GridView1.DataBind();
			}
		}		

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			SelectProcess();
		}

		#endregion		

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;
			int li_curr_month_idx = Convert.ToInt32(DateUtil.GetMonthEx()) + 4;

			string baseYear = ddl_search_base_year.SelectedValue;
			bool isCurrYear = (DateUtil.GetNow("yyyy") == baseYear);

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//계정이름에 링크 걸기
				e.Row.Cells[4].Text
					= "<a href=\"#\" onclick=\"viewChartByAccount('" + e.Row.RowIndex.ToString() + "');\">" + e.Row.Cells[4].Text + "</a>";

				//금액에 링크걸기
				for (int i = 5; i <= 16; i++)
				{
					int m = i - 4;	//인덱스를 월로 변경
					string account = gv.DataKeys[e.Row.RowIndex].Values["Account"].ToString();
					bool isTotal = gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString().EndsWith("T");
					string baseYm = baseYear + ((m < 10) ? "-0" + m.ToString() : "-" + m.ToString());	//2011-04
					string data = e.Row.Cells[i].Text;
					string link = (data == "0" || isTotal) ? "javascript:void(0);" : "javascript:viewDetailList('" + account + "','" + baseYm + "');";

					string finalData = "<span onclick=\"" + link + "\">" + data + "</span>";
					e.Row.Cells[i].Text = finalData;
				}
					
				switch (gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString())
				{
					case "AA001T": //수입합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA002T": //지출합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA002TT": //수입-지출
						e.Row.Attributes.Add("class", "total_v1");
						for (int i = 0; i < e.Row.Cells.Count; i++)
						{
							e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
						}
						break;
					case "AA003T": //저축합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA004T": //수입-저축-지출
						e.Row.Attributes.Add("class", "total_v3");
						for (int i = 0; i < e.Row.Cells.Count; i++)
						{
							e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
						}
						break;
					default:
						e.Row.Cells[li_curr_month_idx].CssClass = isCurrYear ? "bg_peach" : "";
						break;
				}
			}

			//머지
			SMGridView sGv = new SMGridView();
			sGv.RowSpanGridView(GridView1, 2);//2.Class_Nm
		}	

		#endregion

		#region 버튼이벤트

		//전년
		protected void ibtn_prev_year_Click(object sender, EventArgs e)
		{
			SetPrevNextYear(-1);
			SearchProcess();
		}

		//당년
		protected void ibtn_this_year_Click(object sender, EventArgs e)
		{
			SetThisYear();
			SearchProcess();
		}

		//차년
		protected void ibtn_next_year_Click(object sender, EventArgs e)
		{
			SetPrevNextYear(1);
			SearchProcess();
		}

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SetEnabledYearBtn();
			SearchProcess();
		}		

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_base_year", typeof(string), kw1);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			
			using (Mny2011r_NT _Mny2011r_NT = new Mny2011r_NT())
			{
				lo_ds.Merge(_Mny2011r_NT.GetYearlyInOutAnalysisList(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}
		
		//챠트 생성
		protected void lbtn_set_chart_Click(object sender, EventArgs e)
		{
			SetChartByAccount(Convert.ToInt32(h_row_idx.Value));
		}

		//FTP
		protected void ibtn_ftp_Click(object sender, EventArgs e)
		{
			string fileName = PID + ".html";
			FtpClient fc = new FtpClient(FTP_HOSTNAME, FTP_USERID, crypto.Decrypt(FTP_PASSWORD));

			try
			{
				SetSearchParameter();

				DataSet lo_ds = new DataSet();
				DataPack lo_dp = new DataPack();

				lo_dp.AddProperty("ls_base_year", typeof(string), kw1);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				using (Mny2011r_NT _Mny2011r_NT = new Mny2011r_NT())
				{
					lo_ds.Merge(_Mny2011r_NT.GetYearlyInOutAnalysisList(lo_dp));
				}
				//파일생성
				CreateFileReal(fileName, lo_ds);

				//FTP전송
				if (FileUtil.IsFileExist(FILE_PATH_FTP_UPLOAD + "\\" + fileName))
				{
					fc.Login();
					fc.BinaryMode = false;

					string[] remoteDir = StringUtil.DelimitedListToStringArray(FTP_DIR_IPHONE_MNY, "/");
					for (int i = 0; i < remoteDir.Length; i++)
					{
						fc.ChangeDir(remoteDir[i]);
					}
					
					if (fc.IsFileExist(fileName))
					{
						fc.DeleteFile(fileName);
					}

					fc.UploadOnlyFile(FILE_PATH_FTP_UPLOAD, fileName, "", "", true);
					fc.Close();
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_164");	//전송할 파일이 없습니다.
				}
				CallMsgBoxInAjax("MSG_INF_018");	//전송되었습니다
			}
			catch (Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
			finally
			{
				fc.Close();
			}
		}

		#endregion

	}
}
